package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//自定义的全局过滤器
@Slf4j
@Component
@Import(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;

    @Autowired
    private JwtTool jwtTool;

    //过滤器方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //2. 从请求对象中获取请求路径, 如果路径在白名单中, 直接放行
        String path = request.getPath().toString();//请求路径
        for (String excludePath : authProperties.getExcludePaths()) {
            //请求路径如果满足白名单规则,直接放行
            if (new AntPathMatcher().match(excludePath, path)) {
                return chain.filter(exchange);
            }
        }

        //3. 从请求头中获取token,解析并校验token, 如果解析失败, 直接返回401状态码
        String token = request.getHeaders().getFirst("authorization");
        try {
            Long userId = jwtTool.parseToken(token);
            log.info("userId=" + userId);

            //4. 如果校验通过, 将用户id放入请求头传到后面的微服务中
            ServerWebExchange ex = exchange.mutate().request(b -> b.header("user-info", userId.toString())).build();

            //5. 放行
            return chain.filter(ex);
        } catch (UnauthorizedException e) {
            //设置响应状态码401 然后返回响应
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    //这个返回值用于控制当前过滤器在过滤器链中执行的优先级, 数字越小 优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}